import requst from '@/src/utils/requst.js';
import cookie from '@/src/utils/cookie.js';
const APPID = process.env.VUE_APP_WX_APPID;
const WX_AUTH_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID
    + '&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=0#wechat_redirect';
		
/**
 * 微信授权
 */
 const wxAuth = ()=> {
	return new Promise((resolve, reject)=> {
		let openId = cookie.getCookie('openId');
		if(openId) {
			return resolve(openId);
		}
		let code = getUrlParams('code');
		if(!code) {
			// 未经微信授权
			let currentUrl = encodeURIComponent(window.location.href);
			window.location.replace(WX_AUTH_URL.replace('REDIRECT_URI', currentUrl));
		} else {
			 requst.post('/wx/wxAuth/codeToOpenid', {
						code: code
				}).then(res => {
						if (res.code == 200) {
								console.log("微信授权完成");
								resolve(res.data);
						} else {
								console.log("换取openid失败");
						}
				});
		}
	});
}

function getUrlParams(key) {
	const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
	const result = window.location.search.substring(1).match(reg);
	return result ? decodeURIComponent(result[2]) : '';
}

export default wxAuth;